package com.jk.vehicle.mini.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author zhangdongdong
 * @date 2019/7/12
 */
public class XmlUtil {
	/**
	 * 将 xml 字符串 转换为 map
	 <ResponseInfo>   --- xml 字符串
	 <ResCode>Failed</ResCode>
	 <ResMessage>Already in use</ResMessage>
	 <ErrorNo>3</ErrorNo>
	 </ResponseInfo>
	 */
	public static Map<String, Object> parserXmlString(String[] keys, String xml) throws DocumentException{
		Map<String, Object> map = new HashMap<>();
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(
				new ByteArrayInputStream( xml.getBytes() ) );
		Element responseInfo = document.getRootElement();

		for ( int i = 0; i < keys.length; i++ ) {
			String key = keys[i];
			if ( responseInfo.elements( key ).isEmpty() == false ) {
				Element Command = ( Element ) responseInfo.elements( key ).get( 0 );
				Object value = Command.getData();
				map.put( key, value );
			} else {
				map.put( key, "" );
			}
		}

		return map;
	}
}
